<?php
/**
 * @copyright Copyright(c) 2011 aircheng.com
 * @file direct_alipay.php
 * @brief 支付宝插件类[即时到帐]
 * @author nswe
 * @date 2011-01-27
 * @version 0.6
 * @note
 */
require_once 'plugins/WxpayAPI_php_v3/example/log.php';

//初始化日志
$logHandler= new CLogFileHandler("backup/logs/pay_wap_wxpay/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);

 /**
 * @class direct_alipay
 * @brief 支付宝插件类
 */
class wap_wxpay extends paymentPlugin
{
	//支付插件名称
    public $name = 'WAP微信支付';

    /**
     * @brief 构造函数
     * @param $payment_id 支付方式ID
     */
    public function __construct($payment_id)
    {
    	parent::__construct($payment_id);

    	//因为WAP端采用H5单页面，处理略微不一样
    	//同步回调地址
    	$this->callbackUrl         = IUrl::getHost().IUrl::creatUrl("/yunblock/callback/_id/".$payment_id);
    	//回调业务处理地址
    	$this->serverCallbackUrl   = IUrl::getHost().IUrl::creatUrl("/yunblock/server_callback/_id/".$payment_id);
    	// $this->serverCallbackUrl   = IUrl::getHost().'/notify/notify_wechat.php';
    	//中断支付返回
    	$this->merchantCallbackUrl = IUrl::getHost().IUrl::creatUrl("/yunblock/merchant_callback/_id/".$payment_id);
    }

	/**
	 * @see paymentplugin::getSubmitUrl()
	 */
	public function getSubmitUrl()
	{
		return 'https://mapi.alipay.com/gateway.do?_input_charset=utf-8';
	}

	/**
	 * @see paymentplugin::notifyStop()
	 */
	public function notifyStop()
	{
		echo "success";
	}

	/**
	 * @see paymentplugin::callback()
	 */
	public function callback($callbackData,&$paymentId,&$money,&$message,&$orderNo)
	{
		Log::INFO("开始回调处理");
		require_once 'Utils.class.php';
		require_once 'config/Wapwxpayonfig.php';
		require_once 'class/ClientResponseHandler.class.php';
		$resHandler = new ClientResponseHandler();
        $cfg = new Wapwxpayonfig();
        $xml = file_get_contents('php://input');
        Log::INFO($xml);
        $resHandler->setContent($xml);
        $resHandler->setKey($cfg->C('key'));
        if($resHandler->isTenpaySign()){
            if($resHandler->getParameter('status') == 0 && $resHandler->getParameter('result_code') == 0 && $resHandler->getParameter('pay_result') == 0){
            	//回传数据
				$orderNo = $resHandler->getParameter('out_trade_no');
				$money   = $resHandler->getParameter('total_fee');
				$paymentId = 8;
				//记录回执流水号
				if($resHandler->getParameter('transaction_id'))
				{
					$this->recordTradeNo($orderNo,$resHandler->getParameter('transaction_id'));
				}
				Log::INFO('此订单支付状态正常');
				ob_clean();//清理缓冲区
				return true;
            }else{
                return false;
            }
        }else{
           return false;
        }
	}

	/**
	 * @see paymentplugin::serverCallback()
	 */
	public function serverCallback($callbackData,&$paymentId,&$money,&$message,&$orderNo)
	{
		return $this->callback($callbackData,$paymentId,$money,$message,$orderNo);
	}

	/**
	 * @see paymentplugin::getSendData()
	 */
	public function getSendData($payment)
	{
		$return = array();

		//基本参数
		$return['service'] = 'alipay.wap.create.direct.pay.by.user';
		$return['partner'] = $payment['M_PartnerId'];
		$return['seller_id'] = $payment['M_PartnerId'];
		$return['payment_type'] = 1;
		$return['return_url'] = $this->callbackUrl;
		$return['notify_url'] = $this->serverCallbackUrl;
		$return['_input_charset'] = 'utf-8';

		//业务参数
		$return['out_trade_no'] = $payment['M_OrderNO'];//商户订单号，商户网站订单系统中唯一订单号，必填
		$return['subject'] = $payment['R_Name'];//订单名称，必填
		$return['total_fee'] = number_format($payment['M_Amount'], 2, '.', '');//付款金额，必填
		$return['show_url'] = 'http://www.yunguostore.com/index.php';//收银台页面上，商品展示的超链接，必填
		// $return['app_pay'] = 'Y';//启用能唤醒钱包APP支付宝
		$return['body'] = '';//可空

		//除去待签名参数数组中的空值和签名参数
		$para_filter = $this->paraFilter($return);

		//对待签名参数数组排序
		$para_sort = $this->argSort($para_filter);

		//生成签名结果
		$mysign = $this->buildMysign($para_sort, $payment['M_PartnerKey']);

		//签名结果与签名方式加入请求提交参数组中
		$return['sign'] = $mysign;
		$return['sign_type'] = 'MD5';

		return $return;
	}

	public function doPay($sendData)
	{
		require_once 'Utils.class.php';
		require_once 'config/Wapwxpayonfig.php';
		require_once 'class/RequestHandler.class.php';
		require_once 'class/ClientResponseHandler.class.php';
		require_once 'class/PayHttpClient.class.php';
        $resHandler = new ClientResponseHandler();
        $reqHandler = new RequestHandler();
        $pay = new PayHttpClient();
        $cfg = new Wapwxpayonfig();
        $reqHandler->setGateUrl($cfg->C('url'));
        $reqHandler->setKey($cfg->C('key'));

        $reqHandler->setParameter('service','pay.weixin.wappay');//接口类型：pay.weixin.native
        $reqHandler->setParameter('out_trade_no',$sendData['out_trade_no']);
        $reqHandler->setParameter('body',$sendData['out_trade_no']);
        $reqHandler->setParameter('total_fee',$sendData['total_fee'] * 100);
        $reqHandler->setParameter('mch_create_ip',IClient::getIp());
        $reqHandler->setParameter('mch_id',$cfg->C('mchId'));//必填项，商户号，由威富通分配
        $reqHandler->setParameter('version',$cfg->C('version'));

        $notify_url = $this->serverCallbackUrl;

        $siteConfigObj = new Config("site_config");
        $site_config   = $siteConfigObj->getInfo();
        $callback_url = $site_config['url'].IUrl::creatUrl('/site/index/page/'.urlencode('/yunsimple/pay_success'));
        $reqHandler->setParameter('notify_url',$notify_url);
        $reqHandler->setParameter('callback_url',$callback_url);
        $reqHandler->setParameter('nonce_str',mt_rand(time(),time()+rand()));//随机字符串，必填项，不长于 32 位
        $reqHandler->createSign();//创建签名

        $data = Utils::toXml($reqHandler->getAllParameters());
        Log::INFO("begin doPay");
		Log::INFO($data);
        $pay->setReqContent($reqHandler->getGateURL(),$data);
        if($pay->call()){
            $resHandler->setContent($pay->getResContent());
            $resHandler->setKey($reqHandler->getKey());
            if($resHandler->isTenpaySign()){
                if($resHandler->getParameter('status') == 0 ){
                $pay_info = $resHandler->getParameter('pay_info');
				echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
					<html xmlns="http://www.w3.org/1999/xhtml">
						<head></head>
						<body>
						</body>
				    <script type="text/javascript">
					    window.location.href="'.$pay_info.'";
					</script>
					</html>';
                    exit();
                }else{
                    $msg = 'Error Code:'.$resHandler->getParameter('err_code').' Error Message:'.$resHandler->getParameter('err_msg');
                    Log::INFO("【微信wap预支付】失败订单数据:\n".$msg."\n");
                }
            }
            $msg = 'Error Code:'.$resHandler->getParameter('status').' Error Message:'.$resHandler->getParameter('message');
            Log::INFO("【微信wap预支付】失败订单数据:\n".$msg."\n");
        }else{
            $msg = 'Response Code:'.$pay->getResponseCode().' Error Info:'.$pay->getErrInfo();
            Log::INFO("【微信wap预支付】失败订单数据:\n".$msg."\n");
        }
	}

	/**
	 * 除去数组中的空值和签名参数
	 * @param $para 签名参数组
	 * return 去掉空值与签名参数后的新签名参数组
	 */
	private function paraFilter($para)
	{
		$para_filter = array();
		foreach($para as $key => $val)
		{
			if($key == "sign" || $key == "sign_type" || $val == "")
			{
				continue;
			}
			else
			{
				$para_filter[$key] = $para[$key];
			}
		}
		return $para_filter;
	}

	/**
	 * 对数组排序
	 * @param $para 排序前的数组
	 * return 排序后的数组
	 */
	private function argSort($para)
	{
		ksort($para);
		reset($para);
		return $para;
	}

	/**
	 * 生成签名结果
	 * @param $sort_para 要签名的数组
	 * @param $key 支付宝交易安全校验码
	 * @param $sign_type 签名类型 默认值：MD5
	 * return 签名结果字符串
	 */
	private function buildMysign($sort_para,$key,$sign_type = "MD5")
	{
		//把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
		$prestr = $this->createLinkstring($sort_para);
		//把拼接后的字符串再与安全校验码直接连接起来
		$prestr = $prestr.$key;
		//把最终的字符串签名，获得签名结果
		$mysgin = md5($prestr);
		return $mysgin;
	}

	/**
	 * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
	 * @param $para 需要拼接的数组
	 * return 拼接完成以后的字符串
	 */
	private function createLinkstring($para)
	{
		$arg  = "";
		foreach($para as $key => $val)
		{
			$arg.=$key."=".$val."&";
		}

		//去掉最后一个&字符
		$arg = trim($arg,'&');

		//如果存在转义字符，那么去掉转义
		if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
		{
			$arg = stripslashes($arg);
		}

		return $arg;
	}

	/**
	 * @param 获取配置参数
	 */
	public function configParam()
	{
		$result = array(
			'M_PartnerId'  => '合作者身份（PID）',
			'M_PartnerKey' => '安全校验码（Key）',
			'M_Email'      => '登录账号',
		);
		return $result;
	}
}